package com.seeyon.apps.ddkk.manager;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.manager.AdapterSyncDataManager;
import com.seeyon.apps.kk.manager.FreemarkFlowManager;
import com.seeyon.apps.kk.util.JdbcAgentUtil;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.Strings;

public class SyncDDRenewManagerImpl extends AdapterSyncDataManager {

	private static final Log log = LogFactory.getLog(SyncDDRenewManagerImpl.class);
	private FreemarkFlowManager kkFlowManager;
	
	@Override
	public boolean isUnflow() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public String getFormCode() {
		// TODO Auto-generated method stub
		return Constants.ddRenewAlert;
	}

	@Override
	public String getSendUser() {
		// TODO Auto-generated method stub
		return Constants.createUser;
	}

	@Override
	public void delHistoryData() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public List<Map> getSyncData() {
		// TODO Auto-generated method stub
		String path = "ddrenew" + File.separator + "ddrenew.ftl";
		String sql = kkFlowManager.fltTemplateIntoString(path,null);
		try {
			FormBean ddBaseBean = formApi4Cap4.getFormByFormCode(Constants.ddBaseCode);
			String fieldName = ddBaseBean.getFieldBeanByDisplay("经销商组代码").getName();
			Map condition = new HashMap();
			FlipInfo flipInfo = new FlipInfo(1, 200);
			
			List<Map> list = JdbcAgentUtil.doQuery(sql, null);
			for(Map params: list){
				condition.put(fieldName, MapUtils.getObject(params,"udstr_cd"));
				List<FormDataMasterBean> dataList = formApi4Cap4.findMasterDataList(flipInfo , ddBaseBean.getId(), null, condition);
				for(FormDataMasterBean formDataMasterBean: dataList){
					if(MapUtils.getObject(params,"udstr_cd").equals(
							formDataMasterBean.getFieldValue(fieldName))){
						params.put("director", 
								concat2Str(formDataMasterBean, ddBaseBean, new String[] {"BusinessContact", "Contractor", "iChannel_Contact"}));
						params.put("directortelephone", 
								concat2Str(formDataMasterBean, ddBaseBean, new String[] {"BusinessMobile", "ContractorMobile", "iChannel_Mobile"}));
						params.put("directoremail", 
								concat2Str(formDataMasterBean, ddBaseBean, new String[] {"BusinessEmail", "ContractorEmail", "iChannel_Email"}));
						params.put("emaillist", 
								concat2Str(formDataMasterBean, ddBaseBean, new String[] {"DSM_Email"}));
						break;
					}
				}
				int type = MapUtils.getInteger(params,"dealer_type", 0).intValue();
				switch (type) {
					case 1:
						params.put("dstrlvlname", "一级经销商");
						params.put("dealer_type", "经销型");
						break;
					case 2:
						params.put("dstrlvlname", "非一级经销商");
						params.put("dealer_type", "经销型");
						break;
					case 4:
						params.put("dstrlvlname", "强生签约服务商");
						params.put("dealer_type", "物流型");
						break;
					default:
						params.put("dstrlvlname", "非强生签约服务商");
						params.put("dealer_type", "经销型");
						break;
				}
				/*if("北京瑞凯利医疗器械有限责任公司".equals(ParamUtil.getString(params, "udstr_desc_cn", ""))
						|| "上海优铭医疗器械有限公司".equals(ParamUtil.getString(params, "udstr_desc_cn", ""))){
					params.put("directoremail", "837231121@qq.com;xxu34@its.jnj.com;xusf@seeyon.com");
				}*/
			}
			return list;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("##客开异常: ", e);
			return null;
		}
	}

	@Override
	public Map<String, Object> data2FormMap(Map params) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object vaildateDataUnique() {
		// TODO Auto-generated method stub
		return "udstr_cd,dstrlvlname";
	}
	
	public void setKkFlowManager(FreemarkFlowManager kkFlowManager) {
		this.kkFlowManager = kkFlowManager;
	}

	private String concat2Str(FormDataMasterBean dataMaster, FormBean formBean,
				String ...strs){
		String ret = "";
		if(strs != null){
			for(String str: strs){
				if(null != dataMaster.getFieldValue(formBean.getFieldBeanByDisplay(str).getName())
						&& Strings.isNotEmpty(dataMaster.getFieldValue(formBean.getFieldBeanByDisplay(str).getName()).toString())){
					if(Strings.isEmpty(ret)){
						ret = dataMaster.getFieldValue(formBean.getFieldBeanByDisplay(str).getName()).toString();
					} else {
						ret += ";" + dataMaster.getFieldValue(formBean.getFieldBeanByDisplay(str).getName()).toString();
					}
				}
			}
		}
		return ret;
	}
	
	public int saveOrUpdateData(Map<String, Object> params) throws Exception{
		FormBean bean = formApi4Cap4.getFormByFormCode(getFormCode());
		FormDataMasterBean formDataMasterBean = null;
		boolean isMainAdd = false;
		Object unique = vaildateDataUnique();
		if(unique == null){
			isMainAdd = true;
		} else if(unique instanceof String
				|| unique instanceof Map){
			Map<String, Object> vmap = new HashMap<String, Object>();
			String fields = null;
			if(unique instanceof Map){
				fields = ((Map) unique).get("main").toString();
			} else {
				fields = unique.toString();
			}
			for(String fieldDisplay: fields.split(",")){
				FormFieldBean field = bean.getFieldBeanByDisplay(fieldDisplay);
				if(field != null && field.isMasterField()){
					formDataBaseManager.change2Map(field, params.get(fieldDisplay), vmap);
				}
			}
			if(vmap.isEmpty()){
				isMainAdd = true;
			} else {
				FlipInfo flipInfo = new FlipInfo(1, 200);
				List<FormDataMasterBean> masterDataList = formApi4Cap4.findMasterDataList(flipInfo, bean.getId(), null, vmap);
				if(CollectionUtils.isNotEmpty(masterDataList)){
					isMainAdd = true;
					for(FormDataMasterBean dataMaster: masterDataList){
						boolean isUnique = false;
						for(String fieldName: vmap.keySet()){
							if(vmap.get(fieldName) == null
									&& dataMaster.getFieldValue(fieldName) == null){
								isUnique = true;
							} else if(	("dstrlvlname".equals(fieldName) &&
									(("非"+vmap.get(fieldName)).equals(dataMaster.getFieldValue(fieldName))
									|| ("非"+dataMaster.getFieldValue(fieldName)).equals(vmap.get(fieldName))))
									|| vmap.get(fieldName).equals(dataMaster.getFieldValue(fieldName))){
								isUnique = true;
							} else {
								isUnique = false;
								break;
							}
						}
						if(isUnique){
							isMainAdd = false;
							formDataMasterBean = formApi4Cap4.findDataById(dataMaster.getId(), bean, null);
							break;
						}
					}
				} else {
					isMainAdd = true;
				}
			}
		} else {
			isMainAdd = true;
		}
		
		if(isMainAdd){
			try{
				formDataBaseManager.saveUnflowData(getFormCode(), getSendUser(), params);
				return 1;//新增成功
			} catch(Exception e){
				log.error("##客开日志: ", e);
				return 0;//新增失败
			}
		} else {
			String ret = "";
			try{
				if(unique instanceof Map){
					((Map)unique).remove("main");
					ret = formDataBaseManager.updateFormData(getFormCode(), formDataMasterBean, params, (Map)unique);
				} else {
					ret = formDataBaseManager.updateFormData(getFormCode(), formDataMasterBean, params, null);
				}
			} catch(Exception e){
				log.error("##客开日志: ", e);
				return 2;//更新失败
			}
			if(Strings.isEmpty(ret)){
				return 3;//未更新
			} else {
				return 4;//更新成功
			}
		}
	}
}
